const express = require('express')
const router = express.Router()
const connection = require('../mysql')


//! 主界面获取商品列表 --- 火爆推荐
router.get('/goods', (req, res) =>{
    // res.send('ok')
    const sql = 'select * from goodslist'
    connection.query(sql, (err, result) => {
        if (err) return res.status(500).send(err)

        function getRandomObjects(arr, num){
            const shuffled = arr.sort(() => 0.5 - Math.random()); // 随机打乱数组
            return shuffled.slice(0, num); // 取前num个对象
        }
        
        if(result.length > 0){
            // console.log(result);
            const data = getRandomObjects(result, 6); // 随机取6个商品
            res.send({
                status: 200,
                msg: '获取商品列表成功',
                data: data
            })
        }else{
            res.send({
                status: 201,
                msg: '没有获取到商品列表',
                data: []
            })
        }
    })
})  



//! 搜索 -- 获取商品列表
router.get('/searchGoods', (req, res ) =>{

    let key = req.query.searchKey
    const sql = `SELECT * FROM goodslist WHERE g_Name LIKE '%${key}%'`
    // const sql = 'select * from goodsList'
    console.log(req.query.searchKey)

    connection.query(sql, (err, result) => {
        if (err) return res.status(500).send(err)

        if (result.length > 0) {
            res.send({
                status: 200,
                msg: '搜索成功',
                data: result
            })
        }else{
            res.send({
                status: 201,
                msg: '没有搜索到相关商品',
                data: []
            })
        }
        
        
    })
})

//! 详情页 -- 获取商品详情
router.get('/getGoodsDetail', (req, res) =>{
    console.log(req);
    
    let g_id = req.query.g_id

    const sql = 'SELECT * FROM goodslist WHERE g_id = ?'
    connection.query(sql, [g_id], (err, result) => {
        if (err) return res.status(500).send(err)

        console.log(result);
        
        
        if (result.length === 1){
            res.send({
                status: 200,
                msg: '获取商品详情成功',
                data: result[0]
            })
        }else{
            res.send({
                status: 201,
                msg: '没有获取到商品详情',
                data: []
            })
        }
        
        })
    
}) 

module.exports = router;